package com.mrroman.linksender.gui;

import java.awt.AWTException;
import java.awt.Point;
import java.awt.SystemTray;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ResourceBundle;
import java.util.logging.Logger;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.UIManager;

import com.mrroman.linksender.gui.actions.ExitAction;
import com.mrroman.linksender.ioc.Init;
import com.mrroman.linksender.ioc.Locales;
import com.mrroman.linksender.ioc.Log;
import com.mrroman.linksender.ioc.Name;
import com.mrroman.linksender.ioc.ObjectStore;

@Name("gui.MainUI")
public class MainUI {
	
	@Log
	private Logger logger;
	
	@Locales
	private ResourceBundle messages;
	
	@Init
	public void startApp() {
		logger.info(messages.getString("init_style"));
		initStyle();
		
		// check if it is soylatte (Sun Java6 for MacOSX)
//        if ("Darwin".equals(System.getProperty("os.name")) &&
//        		"Sun Microsystems Inc.".equals(System.getProperty("java.vendor"))) {
//        	initMenuWindow();
//        } else {
        	logger.info(messages.getString("init_tray"));
    		initTray();
//        }
	}

	private void initStyle() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}	

	private void initTray() {
		try {
			MyTrayIcon myTrayIcon = ObjectStore.getObject(MyTrayIcon.class);
			SystemTray.getSystemTray().add(myTrayIcon);
		} catch (AWTException e) {
			logger.severe(messages.getString("cannot_put_icon_in_tray") + ": " + e.getMessage());
		}
		
	}
	
	private void initMenuWindow() {
		JFrame menuWindow = new JFrame();
		menuWindow.addWindowListener(new WindowAdapter() {
			@Override
			public void windowClosing(WindowEvent e) {
				ObjectStore.getObject(ExitAction.class).actionPerformed(null);
			}
		});
		
		final JButton button = new JButton(new ImageIcon(getClass().getResource("resources/icon.png")));
		button.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				TrayPopupMenu trayPopupMenu = ObjectStore.getObject(TrayPopupMenu.class);
				Point p = button.getLocationOnScreen();
				
				trayPopupMenu.setLocation((int)p.getX(), (int)p.getY());
				trayPopupMenu.setInvoker(button);
				trayPopupMenu.setVisible(true);
			}
		});
		
		menuWindow.add(button);
		menuWindow.pack();
		menuWindow.setVisible(true);
	}

}
